package com.yzr.common.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Objects;

/**
 * @author yzr
 * @description 固定字段数据填充
 **/
@Component
@Slf4j
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        Object createdBy = metaObject.getValue("createdBy");
        Object modifiedBy = metaObject.getValue("modifiedBy");
        if (Objects.isNull(createdBy)) {
            this.setFieldValByName("createdBy", "UserThreadLocal.get().getUserName()", metaObject);
        }
        if (Objects.isNull(modifiedBy)) {
            this.setFieldValByName("modifiedBy", "UserThreadLocal.get().getUserName()", metaObject);
        }
        LocalDateTime localDateTime = LocalDateTime.now();
        log.debug("数据插入代码生成的时间： " + localDateTime.toString());
        this.setFieldValByName("gmtCreated", localDateTime, metaObject);
        this.setFieldValByName("gmtModified", localDateTime, metaObject);
        Object status = this.getFieldValByName("status", metaObject);
        if (Objects.isNull(status)) {
            this.setFieldValByName("status", 1, metaObject);
        }

    }

    @Override
    public void updateFill(MetaObject metaObject) {
        LocalDateTime localDateTime = LocalDateTime.now();
        this.setFieldValByName("modifiedBy", "UserThreadLocal.get().getUserName()", metaObject);
        this.setFieldValByName("gmtModified", localDateTime, metaObject);
    }

}
